package klk.shop.servlets;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Auf dieses Servlet sind alle Pfade gemappt, die Bilder, CSS und
 * JavaScript enthalten. Diese werden lokal gelesen und auf den Response-
 * Stream geschrieben. Nicht vorhandene Dateien (hier nur Bilder),
 * werden durch ein Standard Bild ersetzt. 
 * @author lueder
 * Servlet implementation class GetImageServlet
 */

public class GetImageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GetImageServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String path = request.getRequestURI().replace(
				request.getContextPath() + "/", "");
		ServletContext context = getServletContext();
		String filename = context.getRealPath(path);

		String mimeType = context.getMimeType(filename);
		if (mimeType == null) {
			context.log("Could not get MIME type of " + filename);
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); //500
			return;
		}
		
		response.setContentType(mimeType);
	
		File file = new File(filename);
		response.setContentLength((int) file.length());


		FileInputStream in = null;
		try {
			in = new FileInputStream(file);
		} catch (FileNotFoundException fnfe) {
			filename = context.getRealPath("images/no-image.jpg");
			mimeType = context.getMimeType(filename);
			response.setContentType(mimeType);
			file = new File(filename);
			response.setContentLength((int) file.length());
			in = new FileInputStream(file);
		}
		OutputStream out = response.getOutputStream();

		// Copy the contents of the file to the output stream
		byte[] buf = new byte[1024];
		int count = 0;
		while ((count = in.read(buf)) >= 0) {
			out.write(buf, 0, count);
		}
		in.close();
		out.close();

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
